package com.gateway.admin.config;

import com.alibaba.fastjson.JSONObject;
import com.gateway.system.domain.dto.BasicRouteDto;
import com.gateway.system.service.BasicRouteService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.cloud.gateway.filter.FilterDefinition;
import org.springframework.cloud.gateway.handler.predicate.PredicateDefinition;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionWriter;
import org.springframework.stereotype.Component;
import org.springframework.web.util.UriComponentsBuilder;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Huangkai
 */
@Component
@Slf4j
public class GateWayInit implements CommandLineRunner {

    @Autowired
    private RouteDefinitionWriter routeDefinitionWriter;

    @Autowired
    BasicRouteService basicRouteService;

    @Override
    public void run(String... args) {
        log.info("网关路由开始加载------------------------");
        loadRouteConfig();
        log.info("网关路由加载结束--------------------------");
    }

    /**
     * 加载路由
     */
    public void loadRouteConfig(){
        List<BasicRouteDto> basicRouteDtoList = basicRouteService.selectBaseRouteList();
        log.info("请求地址{}", basicRouteDtoList);
        if(basicRouteDtoList != null){
            basicRouteDtoList.forEach(basicRouteDto -> {
                RouteDefinition definition = handleData(basicRouteDto);
                routeDefinitionWriter.save(Mono.just(definition)).subscribe();
            });
        }
    }
    public RouteDefinition handleData(BasicRouteDto basicRouteDto){
        RouteDefinition definition = new RouteDefinition();
        //设置id
        definition.setId(String.valueOf(basicRouteDto.getServiceName()));
        URI url = UriComponentsBuilder.fromUriString("lb://" + basicRouteDto.getUri()).build().toUri();
        //判断是否为内部转发，如果是外部转发则进行外部转发，如果是内部转发，则使用lb
        if (basicRouteDto.getUri().startsWith("http") || basicRouteDto.getUri().startsWith("https")) {
            //http地址
            url = UriComponentsBuilder.fromHttpUrl(basicRouteDto.getUri()).build().toUri();
        }
        definition.setUri(url);
        //断言
        PredicateDefinition predicate = new PredicateDefinition();
        predicate.setName("Path");
        Map<String, String> predicateParams = new HashMap<>(8);
        predicateParams.put("pattern", "/" + basicRouteDto.getPredicates() + "/**");
        predicate.setArgs(predicateParams);
        definition.setPredicates(Arrays.asList(predicate));
        //过滤
        FilterDefinition filterDefinition = new FilterDefinition();
        // 名称是固定的, 路径去前缀
        filterDefinition.setName("StripPrefix");
        filterDefinition.addArg("parts", basicRouteDto.getStripPrefix());
        definition.setFilters(Arrays.asList(filterDefinition));

        //优先级
        definition.setOrder(0);

        log.info("值{}", JSONObject.toJSONString(definition));
        return definition;
    }
}
